# -*- coding: utf-8 -*-
"""
农历转换功能
提供阳历农历互转和农历信息查询
"""

import datetime
from typing import Dict, Optional, Tuple
try:
    from zhdate import ZhDate
    ZHDATE_AVAILABLE = True
except ImportError:
    ZHDATE_AVAILABLE = False


class LunarCalendar:
    """农历转换器"""
    
    def __init__(self):
        """初始化农历转换器"""
        self.lunar_months = [
            "正月", "二月", "三月", "四月", "五月", "六月",
            "七月", "八月", "九月", "十月", "十一月", "十二月"
        ]
        
        self.lunar_days = [
            "初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十",
            "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
            "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十"
        ]
        
        self.zodiac_animals = [
            "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"
        ]
        
        # 天干地支
        self.heavenly_stems = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"]
        self.earthly_branches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"]
    
    def solar_to_lunar(self, solar_date) -> Dict:
        """阳历转农历"""
        try:
            if isinstance(solar_date, str):
                solar_date = datetime.datetime.strptime(solar_date, '%Y-%m-%d').date()
            elif hasattr(solar_date, 'date'):
                solar_date = solar_date.date()
            elif not isinstance(solar_date, datetime.date):
                solar_date = datetime.date(solar_date.year, solar_date.month, solar_date.day)
            
            if not ZHDATE_AVAILABLE:
                return self._fallback_solar_to_lunar(solar_date)
            
            # 使用zhdate库进行转换，需要转换为datetime对象
            solar_datetime = datetime.datetime.combine(solar_date, datetime.time())
            zh_date = ZhDate.from_datetime(solar_datetime)
            
            # 获取农历信息
            lunar_year = zh_date.lunar_year
            lunar_month = zh_date.lunar_month
            lunar_day = zh_date.lunar_day
            is_leap_month = zh_date.leap_month
            
            # 格式化显示
            month_name = f"闰{self.lunar_months[lunar_month-1]}" if is_leap_month else self.lunar_months[lunar_month-1]
            day_name = self.lunar_days[lunar_day-1] if lunar_day <= len(self.lunar_days) else f"{lunar_day}日"
            
            # 生肖
            zodiac = self.zodiac_animals[(lunar_year - 4) % 12]
            
            # 天干地支
            stem_index = (lunar_year - 4) % 10
            branch_index = (lunar_year - 4) % 12
            ganzhi = f"{self.heavenly_stems[stem_index]}{self.earthly_branches[branch_index]}"
            
            return {
                'success': True,
                'solar_date': solar_date,
                'lunar_year': lunar_year,
                'lunar_month': lunar_month,
                'lunar_day': lunar_day,
                'is_leap_month': is_leap_month,
                'month_name': month_name,
                'day_name': day_name,
                'zodiac': zodiac,
                'ganzhi': ganzhi,
                'formatted': f"{ganzhi}年（{zodiac}年）{month_name}{day_name}",
                'simple_format': f"{lunar_year}年{month_name}{day_name}"
            }
            
        except Exception as e:
            return {
                'success': False,
                'error': str(e),
                'solar_date': solar_date,
                'formatted': '转换失败',
                'simple_format': '转换失败'
            }
    
    def lunar_to_solar(self, lunar_year: int, lunar_month: int, lunar_day: int, is_leap_month: bool = False) -> Dict:
        """农历转阳历"""
        try:
            if not ZHDATE_AVAILABLE:
                return self._fallback_lunar_to_solar(lunar_year, lunar_month, lunar_day, is_leap_month)
            
            # 使用zhdate库进行转换
            zh_date = ZhDate(lunar_year, lunar_month, lunar_day, is_leap_month)
            solar_date = zh_date.to_datetime().date()
            
            # 格式化显示
            month_name = f"闰{self.lunar_months[lunar_month-1]}" if is_leap_month else self.lunar_months[lunar_month-1]
            day_name = self.lunar_days[lunar_day-1] if lunar_day <= len(self.lunar_days) else f"{lunar_day}日"
            
            # 生肖和天干地支
            zodiac = self.zodiac_animals[(lunar_year - 4) % 12]
            stem_index = (lunar_year - 4) % 10
            branch_index = (lunar_year - 4) % 12
            ganzhi = f"{self.heavenly_stems[stem_index]}{self.earthly_branches[branch_index]}"
            
            return {
                'success': True,
                'solar_date': solar_date,
                'lunar_year': lunar_year,
                'lunar_month': lunar_month,
                'lunar_day': lunar_day,
                'is_leap_month': is_leap_month,
                'month_name': month_name,
                'day_name': day_name,
                'zodiac': zodiac,
                'ganzhi': ganzhi,
                'lunar_formatted': f"{ganzhi}年（{zodiac}年）{month_name}{day_name}",
                'solar_formatted': f"{solar_date.year}年{solar_date.month}月{solar_date.day}日"
            }
            
        except Exception as e:
            return {
                'success': False,
                'error': str(e),
                'lunar_formatted': '转换失败',
                'solar_formatted': '转换失败'
            }
    
    def _fallback_solar_to_lunar(self, solar_date) -> Dict:
        """简化版阳历转农历（当zhdate库不可用时）"""
        # 这里提供一个基础的近似转换
        # 实际应用中建议使用专业的农历库
        year = solar_date.year
        zodiac = self.zodiac_animals[(year - 4) % 12]
        stem_index = (year - 4) % 10
        branch_index = (year - 4) % 12
        ganzhi = f"{self.heavenly_stems[stem_index]}{self.earthly_branches[branch_index]}"
        
        return {
            'success': False,
            'solar_date': solar_date,
            'lunar_year': year,
            'lunar_month': 1,
            'lunar_day': 1,
            'is_leap_month': False,
            'month_name': "正月",
            'day_name': "初一",
            'zodiac': zodiac,
            'ganzhi': ganzhi,
            'formatted': f"{ganzhi}年（{zodiac}年）农历转换需要安装zhdate库",
            'simple_format': "需要安装zhdate库",
            'error': "zhdate库未安装，无法进行精确转换"
        }
    
    def _fallback_lunar_to_solar(self, lunar_year: int, lunar_month: int, lunar_day: int, is_leap_month: bool) -> Dict:
        """简化版农历转阳历（当zhdate库不可用时）"""
        return {
            'success': False,
            'error': "zhdate库未安装，无法进行农历转阳历转换",
            'lunar_formatted': "需要安装zhdate库",
            'solar_formatted': "需要安装zhdate库"
        }
    
    def get_lunar_info(self, date_obj) -> Dict:
        """获取指定日期的农历信息"""
        lunar_result = self.solar_to_lunar(date_obj)
        if lunar_result['success']:
            return {
                'has_lunar': True,
                'lunar_date': lunar_result['formatted'],
                'lunar_simple': lunar_result['simple_format'],
                'zodiac': lunar_result['zodiac'],
                'ganzhi': lunar_result['ganzhi'],
                'is_leap_month': lunar_result['is_leap_month']
            }
        else:
            return {
                'has_lunar': False,
                'lunar_date': lunar_result.get('formatted', '转换失败'),
                'lunar_simple': lunar_result.get('simple_format', '转换失败'),
                'zodiac': '未知',
                'ganzhi': '未知',
                'is_leap_month': False,
                'error': lunar_result.get('error', '转换失败')
            }
    
    def is_zhdate_available(self) -> bool:
        """检查zhdate库是否可用"""
        return ZHDATE_AVAILABLE
